package net.risesoft.risebi.collection.web.admin;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import net.risesoft.risebi.collection.model.Application;
import net.risesoft.risebi.collection.model.Department;
import net.risesoft.risebi.collection.model.Employee;
import net.risesoft.risebi.collection.model.ObjectPermission;
import net.risesoft.risebi.collection.model.Role;
import net.risesoft.risebi.collection.model.Service;
import net.risesoft.risebi.collection.model.Template;
import net.risesoft.risebi.collection.model.User;
import net.risesoft.risebi.collection.service.ApplicationManager;
import net.risesoft.risebi.collection.service.DepartmentManager;
import net.risesoft.risebi.collection.service.ModuleManager;
import net.risesoft.risebi.collection.service.ObjectPermissionManager;
import net.risesoft.risebi.collection.service.PrivilegeManager;
import net.risesoft.risebi.collection.service.RoleManager;
import net.risesoft.risebi.collection.service.ServiceManager;
import net.risesoft.risebi.collection.service.SpecialityManager;
import net.risesoft.risebi.collection.service.TemplateIndicationManager;
import net.risesoft.risebi.collection.service.TemplateManager;
import net.risesoft.risebi.collection.service.UserManager;
import net.risesoft.risebi.collection.web.BaseAction;
import net.risesoft.risebi.commons.util.GUID;
import net.risesoft.risebi.commons.util.JSONUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.beanutils.LazyDynaBean;
import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;

/**
*
* @author <a href="mailto: dingzhaojun2046@hotmail.com">丁兆俊</a>
* @version $Revision$
* 
*/
@Namespace("/admin/PermissionAction")
public class PermissionAction extends BaseAction {
	private static final Logger logger = Logger.getLogger(PermissionAction.class);
	private static final long serialVersionUID = -5580842611301789909L;
	
	private ObjectPermissionManager objectPermissionManager;
	private RoleManager roleManager;
	private UserManager userManager;
	private DepartmentManager departmentManager;
	private PrivilegeManager privilegeManager;
	private ModuleManager moduleManager;
	private ApplicationManager applicationManager;
	private TemplateManager templateManager;
	private SpecialityManager specialityManager;
	private TemplateIndicationManager templateIndicationManager;
	private ServiceManager serviceManager;
	
	private User user;
	private ObjectPermission objectPermission;
	
	private int objectType;
	private String objectGuid;
	private String jsonObjectPermissions;	
	private String serviceGuid = "";
	private boolean serviceUser = false;
	private boolean topModule = false;	

	@Action(value="prepareEdit",
			results={@Result(name="success", location="/admin/permission/permissionEdit.jsp")}
	)
	public String prepareEdit() throws Exception {
		if("currentServiceGuid".equals(this.objectGuid)){
			this.objectGuid = this.getDefaultService().getGuid();
		}
		
		this.serviceGuid = "";
		if(this.getDefaultService()!=null){
			this.serviceGuid = this.getDefaultService().getGuid();
		}
		
		return SUCCESS;
	}

	@Action(value="prepareEdit4Module",
			results={@Result(name="success", location="/admin/permission/permissionEdit4Module.jsp")}
	)
	public String prepareEdit4Module() throws Exception {
		List list = serviceManager.getServicesWithPermission(this.getSessionUser());
		
		this.serviceGuid = "";
		if(this.serviceUser==true && this.getDefaultService()!=null){
			this.serviceGuid = this.getDefaultService().getGuid();
		}
		
		this.json = JSONUtil.getJsonString("include", "guid,name", list);
		return SUCCESS;
	}
	
	@Action(value="remove")
	public String remove() throws Exception {
		LazyDynaBean ldb = new  LazyDynaBean();
		try{
			objectPermissionManager.removeObject(ObjectPermission.class, node); 		
			
			ldb.set("success", true);
			ldb.set("reason", "删除成功!");
			this.json = JSONObject.fromObject(ldb).toString();
		}catch(Exception e){
			ldb.set("success", false);
			ldb.set("reason", e.getMessage());
			this.json = JSONObject.fromObject(ldb).toString();
		}

		return AJAX;
	}

	@Action(value="removeAll")
	public String removeAll() throws Exception {
		LazyDynaBean ldb = new  LazyDynaBean();
		try{
			objectPermissionManager.execute("delete from ObjectPermission p where p.objectGuid='" + this.objectGuid + "'");
			
			ldb.set("success", true);
			ldb.set("reason", "删除成功!");
			this.json = JSONObject.fromObject(ldb).toString();
		}catch(Exception e){
			ldb.set("success", false);
			ldb.set("reason", e.getMessage());
			this.json = JSONObject.fromObject(ldb).toString();
		}

		return AJAX;
	}

	@Action(value="insertOrUpdatePermission4Module")
	public String insertOrUpdatePermission4Module() throws Exception {
		LazyDynaBean ldb = new  LazyDynaBean();
		try{
			if(this.jsonObjectPermissions.trim().length()>0){
				ObjectPermission[] ps = (ObjectPermission[])JSONUtil.stringToArray(this.jsonObjectPermissions, ObjectPermission.class);
				for (ObjectPermission p : ps){
					if(p.getGuid()==null || p.getGuid().length()==0 || p.getGuid().startsWith("NEW")){
						p.setGuid(new GUID().toString());
					}
					
					if(p.getObjectGuid()==null || p.getObjectGuid().length()==0){
						p.setObjectGuid(this.objectGuid);
					}
					
					objectPermissionManager.saveObject(p);
				}
			}
			
			ldb.set("success", true);
			ldb.set("reason", "修改许可成功!");
			this.json = JSONObject.fromObject(ldb).toString();
		}catch(Exception e){

			ldb.set("success", false);
			ldb.set("reason", e.getMessage());
			this.json = JSONObject.fromObject(ldb).toString();
			e.printStackTrace();
		}

		return AJAX;
	}
	
	@Action(value="insertOrUpdatePermission")
	public String insertOrUpdatePermission() throws Exception {
		LazyDynaBean ldb = new  LazyDynaBean();
		try{
			if(this.jsonObjectPermissions.trim().length()>0){
				ObjectPermission[] ps = (ObjectPermission[])JSONUtil.stringToArray(this.jsonObjectPermissions, ObjectPermission.class);
				for (ObjectPermission p : ps){
					if(p.getGuid()==null || p.getGuid().length()==0 || p.getGuid().startsWith("NEW")){
						p.setGuid(new GUID().toString());
					}
					
					if(p.getObjectGuid()==null || p.getObjectGuid().length()==0){
						p.setObjectGuid(this.objectGuid);
					}
					
					if(this.getDefaultService()!=null){
						p.setServiceGuid(this.getDefaultService().getGuid());
					}					
					
					objectPermissionManager.saveObject(p);
				}
			}
			
			ldb.set("success", true);
			ldb.set("reason", "修改许可成功!");
			this.json = JSONObject.fromObject(ldb).toString();
		}catch(Exception e){

			ldb.set("success", false);
			ldb.set("reason", e.getMessage());
			this.json = JSONObject.fromObject(ldb).toString();
			e.printStackTrace();
		}

		return AJAX;
	}
	
	@Action(value="prepareAddRole",
			results={@Result(name="success", location="/admin/permission/permissionAddRole.jsp")}
	)
	public String prepareAddRole() throws Exception {

		return SUCCESS;
	}

	@Action(value="prepareAddUser",
			results={@Result(name="success", location="/admin/permission/permissionAddUser.jsp")}
	)
	public String prepareAddUser() throws Exception {

		return SUCCESS;
	}

	@Action(value="prepareAddDepartment",
			results={@Result(name="success", location="/admin/permission/permissionAddDepartment.jsp")}
	)
	public String prepareAddDepartment() throws Exception {

		return SUCCESS;
	}

	@Action(value="refreshJson")
	public String refreshJson() throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("refreshJson() - start"); //$NON-NLS-1$
		}

		try{
			if("jsonPermissions".equalsIgnoreCase(this.whichJson)){
				if(objectPermission==null) objectPermission = new ObjectPermission();
				objectPermission.setObjectGuid(objectGuid);
				
				Map map = objectPermissionManager.getPagedResultByObject(objectPermission, "u", "", start, limit);				
				this.json = JSONUtil.getJsonString("include", "count,list,guid,serviceGuid,principalGuid,principalType,principalName,objectGuid,objectType,permission,inherited", map);
			}else if("jsonRoles".equalsIgnoreCase(this.whichJson)){
				List<Role> lst = null;
				
				String hql = "from Role r where 1=1";
				if(this.serviceGuid != null && this.serviceGuid.trim().length()>0){
					hql += " and r.service.guid='" + this.serviceGuid + "'";
				}
				
				if(this.source != null && this.source.equalsIgnoreCase("manager")){
					lst = roleManager.find(hql + " and r.type=1 and r.guid not in ( select p.principalGuid from ObjectPermission p where p.principalType=1 and p.objectGuid='" + this.objectGuid + "')");
				}else{
					lst = roleManager.find(hql + " and r.guid not in ( select p.principalGuid from ObjectPermission p where p.principalType=1 and p.objectGuid='" + this.objectGuid + "')");
				}
				
				this.json = JSONUtil.getJsonString("include", "guid,parentGuid,name,type,dynamic,policy,tabIndex", lst);				
			}else if("jsonUsers".equalsIgnoreCase(this.whichJson)){				
				Map map = null;
				String filter = "";
				
				if(this.user==null){
					user = new User();
				}
				
				if(this.source != null && this.source.equalsIgnoreCase("so")){
					user.setUserType(2);
				}else if(this.source != null && this.source.equalsIgnoreCase("manager")){
					user.setUserType(1);
					if(this.serviceGuid != null && this.serviceGuid.trim().length()>0){
						Service s = new Service();
						s.setGuid(this.serviceGuid);
						
						Employee e = new Employee();
						//e.setService(s);
						user.setEmployee(e);
					}
				}
				filter = "u.guid not in (select p.principalGuid from ObjectPermission p where p.principalType=3 and p.objectGuid='" + this.objectGuid + "')";
				map = userManager.getAllUser(user, "u", filter, start, limit);
				this.json = JSONUtil.getJsonString("include", "count,list,guid,name,realName,enabled,authentication_type,userType,openAccountType,tabIndex", map);
			}else if("jsonDepartments".equalsIgnoreCase(this.whichJson)){
				List<Department> lst = departmentManager.find("from Department d");
				if(this.serviceGuid != null && this.serviceGuid.trim().length()>0){
					lst = departmentManager.find("from Department d where d.service.guid='" + this.serviceGuid + "'");
				}
				
				JSONArray jsonArray = new JSONArray();
				for(Department d : lst){
					JSONObject jsonObject = new JSONObject();
					jsonObject.element("guid", d.getGuid());
					jsonObject.element("parentGuid", d.getParentGuid());
					jsonObject.element("name", d.getName());

					boolean checked = false;
					int count = objectPermissionManager.getCount("select count(*) from ObjectPermission t where t.principalType=2 and t.objectGuid='" + this.objectGuid + "' and t.principalGuid='" + d.getGuid() + "'");
					if(count>0){
						checked = true;
					}
					
					jsonObject.element("checked", checked);	
					jsonArray.add(jsonObject);
				}	
				this.json = jsonArray.toString();
			}else if("jsonApps".equalsIgnoreCase(this.whichJson)){
				List<Application> lst = applicationManager.getObjects(Application.class);
				this.json = JSONUtil.getJsonString("include", "guid,chineseName", lst);				
			}else if("jsonApplications".equalsIgnoreCase(this.whichJson)){
				ArrayList al = new ArrayList();		
				/*
		    	1:'模块';
		    	2:'操作';
		    	3:'应用';
		    	4:'服务';
		    	5:'模版';
		    	6:'元素';
		    	*/

				if(this.active_node_id==null){
					List<Application> lst = applicationManager.getAllOrderByTabIndex();
					for(Application a : lst){
						boolean isleaf = true;
						List<Template> lst1 = templateManager.getTemplatesByApplication(a.getGuid());
						if(lst1.size()>0){
							isleaf = false;
						}
						LazyDynaBean ldb = new LazyDynaBean();
						ldb.set("guid", a.getGuid());
						ldb.set("parentGuid", "");
						ldb.set("name", a.getChineseName());
						ldb.set("_node_type", "3");
						ldb.set("_is_leaf", isleaf);
						al.add(ldb);
					}					
				}else if("3".equalsIgnoreCase(this.active_node_type)){
					List<Template> lst = templateManager.getTemplatesByApplication(this.active_node_id);
					for(Template a : lst){
						LazyDynaBean ldb = new LazyDynaBean();
						ldb.set("guid", a.getGuid());
						ldb.set("parentGuid", this.active_node_id);
						ldb.set("name", a.getName());
						ldb.set("_node_type", "5");
						ldb.set("_is_leaf", true);
						al.add(ldb);
					}					
				}				

				this.json = JSONUtil.getJsonString(null, null, al);				
			}
		}catch(Exception e){
			logger.error("refreshJson()", e); //$NON-NLS-1$

			this.json = "[]";
			e.printStackTrace();
		}
 

		if (logger.isDebugEnabled()) {
			logger.debug("refreshJson() - end"); //$NON-NLS-1$
		}
		return AJAX;
	}

	public ObjectPermissionManager getObjectPermissionManager() {
		return objectPermissionManager;
	}

	public void setObjectPermissionManager(
			ObjectPermissionManager objectPermissionManager) {
		this.objectPermissionManager = objectPermissionManager;
	}

	public RoleManager getRoleManager() {
		return roleManager;
	}

	public void setRoleManager(RoleManager roleManager) {
		this.roleManager = roleManager;
	}

	public UserManager getUserManager() {
		return userManager;
	}

	public void setUserManager(UserManager userManager) {
		this.userManager = userManager;
	}

	public ModuleManager getModuleManager() {
		return moduleManager;
	}

	public void setModuleManager(ModuleManager moduleManager) {
		this.moduleManager = moduleManager;
	}

	public ApplicationManager getApplicationManager() {
		return applicationManager;
	}

	public void setApplicationManager(ApplicationManager applicationManager) {
		this.applicationManager = applicationManager;
	}

	public TemplateManager getTemplateManager() {
		return templateManager;
	}

	public void setTemplateManager(TemplateManager templateManager) {
		this.templateManager = templateManager;
	}

	public SpecialityManager getSpecialityManager() {
		return specialityManager;
	}

	public void setSpecialityManager(SpecialityManager specialityManager) {
		this.specialityManager = specialityManager;
	}

	public TemplateIndicationManager getTemplateIndicationManager() {
		return templateIndicationManager;
	}

	public void setTemplateIndicationManager(
			TemplateIndicationManager templateIndicationManager) {
		this.templateIndicationManager = templateIndicationManager;
	}

	public String getObjectGuid() {
		return objectGuid;
	}

	public void setObjectGuid(String objectGuid) {
		this.objectGuid = objectGuid;
	}

	public String getJsonObjectPermissions() {
		return jsonObjectPermissions;
	}

	public void setJsonObjectPermissions(String jsonObjectPermissions) {
		this.jsonObjectPermissions = jsonObjectPermissions;
	}

	public static long getSerialVersionUID() {
		return serialVersionUID;
	}

	public int getObjectType() {
		return objectType;
	}

	public void setObjectType(int objectType) {
		this.objectType = objectType;
	}

	public DepartmentManager getDepartmentManager() {
		return departmentManager;
	}

	public void setDepartmentManager(DepartmentManager departmentManager) {
		this.departmentManager = departmentManager;
	}

	public PrivilegeManager getPrivilegeManager() {
		return privilegeManager;
	}

	public void setPrivilegeManager(PrivilegeManager privilegeManager) {
		this.privilegeManager = privilegeManager;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public ObjectPermission getObjectPermission() {
		return objectPermission;
	}

	public void setObjectPermission(ObjectPermission objectPermission) {
		this.objectPermission = objectPermission;
	}

	public ServiceManager getServiceManager() {
		return serviceManager;
	}

	public void setServiceManager(ServiceManager serviceManager) {
		this.serviceManager = serviceManager;
	}

	public String getServiceGuid() {
		return serviceGuid;
	}

	public void setServiceGuid(String serviceGuid) {
		this.serviceGuid = serviceGuid;
	}

	public boolean isServiceUser() {
		return serviceUser;
	}

	public void setServiceUser(boolean serviceUser) {
		this.serviceUser = serviceUser;
	}

	public boolean isTopModule() {
		return topModule;
	}

	public void setTopModule(boolean topModule) {
		this.topModule = topModule;
	}

}
